//
//  TSBasePageVC.swift
//  Pods
//
//  Created by 100Years on 2025/8/4.
//

import UIKit

open class TSBasePageVC: UIPageViewController,UIPageViewControllerDataSource {
    
    open var dataItems: [Any] = []/// 数据源数组
    open var currentIndex: Int = 0/// 当前索引
    open var currentIndexChanged:((Int)->Void)?
    
    // MARK: - Initialization
    public convenience init(
        dataItems: [Any],
        startIndex: Int = 0,
        navigationOrientation:NavigationOrientation = .horizontal,
        currentIndexChanged:((Int)->Void)? = nil) {
        // 完全依赖系统自动处理 RTL 方向
        self.init(transitionStyle: .scroll, navigationOrientation: navigationOrientation)
        self.dataItems = dataItems
        self.currentIndex = startIndex
        self.currentIndexChanged = currentIndexChanged
    }
    
    // MARK: - Lifecycle
    
    open override func viewDidLoad() {
        super.viewDidLoad()
        setupPageViewController()
        dealThings()
    }
    
    
    open func dealThings()  { }
    
    // MARK: - Setup
    
    private func setupPageViewController() {

        dataSource = self
        delegate = self
        
        // 设置初始视图控制器
        if let initialVC = viewController(at: currentIndex) {
            setViewControllers([initialVC], direction: .forward, animated: true, completion: nil)
        }
    }
    
    // MARK: - Public Methods
    
    /// 获取指定索引的视图控制器（子类需重写）
    open func viewController(at index: Int) -> UIViewController? {
        // 子类实现具体逻辑
        return nil
    }
    
    /// 跳转到指定页面
    public func goToPage(at index: Int, animated: Bool = true) {
        guard index >= 0 && index < dataItems.count else { return }
        
        let direction: UIPageViewController.NavigationDirection = index > currentIndex ? .forward : .reverse
        currentIndex = index
        
        if let vc = viewController(at: index) {
            setViewControllers([vc], direction: direction, animated: animated) { _ in
                // 确保页面切换完成
                self.currentIndex = index
            }
        }
    }

    
    
    public func pageViewController(_ pageViewController: UIPageViewController, viewControllerBefore viewController: UIViewController) -> UIViewController? {
        guard let index = indexOfViewController(viewController) else { return nil }
        return index > 0 ? self.viewController(at: index - 1) : nil
    }
    
    public func pageViewController(_ pageViewController: UIPageViewController, viewControllerAfter viewController: UIViewController) -> UIViewController? {
        guard let index = indexOfViewController(viewController) else { return nil }
        return index < dataItems.count - 1 ? self.viewController(at: index + 1) : nil
    }
    
    /// 获取视图控制器对应的索引（子类需重写）
    open func indexOfViewController(_ viewController: UIViewController) -> Int? {
        // 子类实现具体逻辑
        return nil
    }
    
    /// 删除指定索引的页面
    open func removePage(at index: Int, animated: Bool = true) {
        guard index >= 0 && index < dataItems.count else { return }
        
        // 1. 从数据源移除
        dataItems.remove(at: index)
        
        // 2. 处理当前索引
        if currentIndex == index {
            // 如果删除的是当前页，需要决定跳转到哪页
            let newIndex = min(index, dataItems.count - 1)
            if newIndex >= 0 {
                goToPage(at: newIndex, animated: animated)
            } else {
                // 没有页面了，可以关闭浏览器或显示空白页
                setViewControllers([UIViewController()], direction: .forward, animated: animated)
            }
        } else if currentIndex > index {
            // 如果删除的是前面的页面，调整当前索引
            currentIndex -= 1
        }
    }
    
    /// 删除当前显示的页面
    open func removeCurrentPage(animated: Bool = true) {
        removePage(at: currentIndex, animated: animated)
    }
    
    open var currentPageVC:UIViewController?{
        return viewControllers?.first
    }
}

// MARK: - UIPageViewControllerDelegate
extension TSBasePageVC: UIPageViewControllerDelegate {
    public func pageViewController(_ pageViewController: UIPageViewController, didFinishAnimating finished: Bool, previousViewControllers: [UIViewController], transitionCompleted completed: Bool) {
        if completed, let currentVC = viewControllers?.first, let index = indexOfViewController(currentVC) {
            currentIndex = index
            currentIndexChanged?(index)
        }
    }
}
